<template>
  <div>
    <!-- 路径 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加用户 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <!-- 数据展示区域 -->
      <template>
        <el-table :data="rolesList" style="width: 100%" border>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-row
                type="flex"
                align="middle"
                :class="[index1 === 0 ? 'row-top' : '', 'row-bottom']"
                v-for="(item1, index1) in scope.row.children"
                :key="item1.id"
              >
                <el-col :span="5">
                  <el-tag closable @close="removeRight(scope.row, item1.id)">{{
                    item1.authName
                  }}</el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="19">
                  <el-row
                    type="flex"
                    align="middle"
                    :class="[index2 === 0 ? '' : 'row-top']"
                    v-for="(item2, index2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="7">
                      <el-tag
                        type="success"
                        closable
                        @close="removeRight(scope.row, item2.id)"
                        >{{ item2.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="17">
                      <el-tag
                        type="warning"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        closable
                        @close="removeRight(scope.row, item3.id)"
                      >
                        {{ item3.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作" width="175px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="editRole(scope.row.id)"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="removeRole(scope.row.id)"
              ></el-button>
              <el-tooltip
                effect="dark"
                content="设置角色权限"
                placement="top"
                :enterable="false"
              >
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-setting"
                  @click="settingRoleRights(scope.row)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-card>

    <!-- 添加角色 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%">
      <!-- 主体部分 -->
      <el-form
        ref="addFormRef"
        :model="addRoleForm"
        :rules="addRoleRules"
        label-width="100px"
        @closed="resetAddForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addFormInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%">
      <!-- 主体部分 -->
      <el-form
        ref="editFormRef"
        :model="editRoleForm"
        :rules="editRoleRules"
        label-width="100px"
        @closed="resetEditForm"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置角色权限对话框 -->
    <el-dialog
      title="设置角色权限"
      :visible.sync="settingDialogVisible"
      width="50%"
      @closed="resetCheckIds"
    >
      <!-- 主体部分 -->
      <el-tree
        :data="rightsList"
        :props="rightsProps"
        node-key="id"
        :default-checked-keys="checkedIds"
        default-expand-all
        show-checkbox
        check-on-click-node
        ref="treeRef"
      ></el-tree>
      <!-- 底部按钮 -->
      <span slot="footer">
        <el-button @click="settingDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="settingInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  created() {
    this.queryRolesList()
  },
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 权限列表
      rightsList: [],
      // 树形控件绑定设置
      rightsProps: {
        children: 'children',
        label: 'authName',
      },
      // 控制角色编辑对话框的显示
      editDialogVisible: false,
      // 修改角色
      editRoleForm: {},
      // 修改角色表单验证
      editRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 添加角色对话框显示
      addDialogVisible: false,
      // 添加角色的数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加角色的规则
      addRoleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 控制设置角色权限对话框显示
      settingDialogVisible: false,
      // 设置角色权限页面角色权限的id集合数组
      checkedIds: [],
      // 存储设置角色时角色的id
      settingRoleId:''
    }
  },
  methods: {
    // 获取角色列表
    async queryRolesList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200)
        return this.$message.error('请求角色列表失败！')
      this.rolesList = res.data
    },
    // 修改角色
    async editRole(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('查询角色失败！')
      this.editRoleForm = res.data
      this.editDialogVisible = true
    },
    // 清空编辑表单
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 提交编辑表单
    editFormInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            'roles/' + this.editRoleForm.roleId,
            {
              roleName: this.editRoleForm.roleName,
              roleDesc: this.editRoleForm.roleDesc,
            }
          )
          if (res.meta.status !== 200)
            return this.$message.error('修改角色失败！')
          this.$message.success('修改角色成功！')
          this.queryRolesList()
          this.editDialogVisible = false
        }
      })
    },
    // 清空添加表单
    resetAddForm() {
      this.$refs.addFormRef.resetFields()
    },
    // 提交添加角色
    addFormInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.post('roles', this.addRoleForm)
          if (res.meta.status !== 201)
            return this.$message.error('添加角色失败！')
          this.$message.success('添加角色成功！')
          this.queryRolesList()
          this.addDialogVisible = false
        }
      })
    },
    // 删除角色
    removeRole(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('roles/' + id)
          if (res.meta.status !== 200)
            return this.$message.error('删除角色失败！')
          this.$message.success('删除角色成功！')
          this.queryRolesList()
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },
    // 删除权限
    removeRight(role, rightId) {
      this.$confirm('此操作将删除角色权限, 是否继续?', '删除角色', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200)
            return this.$message.error('删除角色权限失败！')
          this.$message.success('删除角色权限成功！')
          // this.queryRolesList()
          role.children = res.data
        })
        .catch(() => {
          this.$message.info('已取消删除！')
        })
    },
    // 获取权限列表
    async queryRightsList() {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) this.$message.error('获取权限列表失败！')
      this.rightsList = res.data
    },
    // 设置回调函数获取id集合
    getIdsArr(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getIdsArr(item, arr))
    },
    // 设置角色权限
    settingRoleRights(role) {
      this.settingRoleId=role.id
      this.getIdsArr(role, this.checkedIds)
      this.queryRightsList()
      this.settingDialogVisible = true
    },
    // 关闭编辑角色权限列表后清空默认选择id
    resetCheckIds() {
      this.checkedIds = []
    },
    // 提交设置角色权限
    async settingInfo() {
      const newArr=[...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()]
      const newStr=newArr.join(',')
      const {data:res}=await this.$http.post(`roles/${this.settingRoleId}/rights`,{rids:newStr})
      if(res.meta.status!==200) return this.$message.error('提交角色权限失败！')
      this.$message.success('提交角色权限成功！')
      this.queryRolesList()
      this.settingDialogVisible=false
    },
  },
}
</script>

<style lang="less" scoped>
.el-row {
  padding: 10px;
}
.el-tag {
  margin: 5px;
}
.row-top {
  border-top: 1px solid #eee;
}
.row-bottom {
  border-bottom: 1px solid #eee;
}
</style>